package com.example.common.mvi

import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.common.base.BaseFragment
import com.example.common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviFragment<T:ViewDataBinding>:BaseFragment<T>() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        updataUI()
        //注册EventBus
        EventBus.getDefault().register(this)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
     fun receiveEvent(event: CustomEvent) {
        if (event != null && event.target == this::class.java.simpleName){
            handEvent(event)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //一定反注册,避免内存泄漏
        EventBus.getDefault().unregister(this)
    }
    private fun initData(){
        lifecycleScope.launch {
            sendViewIntent()
        }
    }
    private fun updataUI(){
        lifecycleScope.launch {
            //指定在Activity执行到某个生命周期时收集数据状态
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUIState()
            }
        }
    }
    /**
     * (open修饰）子类可以有选择性重写该方法
     */
    open suspend fun sendViewIntent(){

    }
    open suspend fun collectUIState(){

    }
    open  fun handEvent(event: CustomEvent){

    }


}